package com.demo.function.shiro.jwt;

import cn.hutool.core.lang.Assert;
import com.demo.function.mybatis.mybatisplus.service.UserService;
import com.demo.model.entity.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class JWTRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 重写supports方法，告诉shiro当前Realm只支持JWTToken
     * @param token the token being submitted for authentication.
     * @return true if this Realm supports the specified token, false otherwise.
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 获取授权数据(角色权限信息)
     * @param principalCollection the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return AuthorizationInfo对象
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 这里获取的值为什么是User对象，因为在doGetAuthenticationInfo方法里返回SimpleAuthenticationInfo，
        // SimpleAuthenticationInfo里创建了SimplePrincipalCollection，SimplePrincipalCollection是实现了接口PrincipalCollection
        User user = (User) principalCollection.getPrimaryPrincipal();
        Set<String> permsSet = Arrays.stream(user.getPermissions().split(",")).collect(Collectors.toSet());

        // 请求接口使用注解@RequiresPermissions并设置访问权限标识，用户拥有该标识才能访问
        // 设置用户访问权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 获取认证的安全数据（从数据库查询到的用户正确数据）
     * @param authenticationToken the authentication token containing the user's principal and credentials.
     * @return AuthenticationInfo对象
     * @throws AuthenticationException 异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 这里获取的principal就是JWTToken类设置的值，JWTToken是在JWTFilter#executeLogin方法中调用createToken方法
        String id = (String) authenticationToken.getPrincipal();
        log.info("principal:{}",  id);

        User user = userService.getById(id);
        Assert.notNull(user, () -> new AuthenticationException("用户不存在"));
        return new SimpleAuthenticationInfo(user, id, this.getName());
    }
}
